/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.CommonUtil;
import com.star.common.PostData;
import com.star.common.RenderModel;
import com.start.model.PostModel;
import com.start.model.SessionModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminNewsUserController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AdminNewsUserController.class);
    private static final int NEWS_PER_PAGE = 10;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminNewsUserController.handle:" + ex.getMessage(), ex);
        }
    }
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) { 
            case "/search":
                content = renderSearchPage(req, resp);
                break;                
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);            

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "newsuser"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin đã post");
            //dic.showSection("NEWSTYPE");
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
                 
            SessionModel sessionModel = SessionModel.getInstance();                
            String userLogin = sessionModel.getUserLogin(req);
            PostModel postModel = PostModel.getInstance();                
            List<PostData> lstPost = postModel.getPost((page - 1) * NEWS_PER_PAGE, NEWS_PER_PAGE, "", "", 
                    userLogin, "", "", "", "");            
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            if (lstPost != null && !lstPost.isEmpty()) {
                for (PostData postData : lstPost) {                    
                    TemplateDataDictionary section = dic.addSection("LIST_NEWS");                    
                    section.setVariable("NEWS_LINK", "/post/edit?id=" + postData.getId());  
                    section.setVariable("NEWS_TITLE", postData.getTitle()); 
                    Date d = new Date(postData.getCreated());
                    section.setVariable("CREATED", sdf.format(d));
                    if (postData.getStatus() == 0) {
                        section.setVariable("STATUS", "Chờ duyệt");
                        section.showSection("WARNING");
                    } else if (postData.getStatus() == 1){
                        section.setVariable("STATUS", "Công khai");
                    }
                    else {
                        section.setVariable("STATUS", "Ẩn");
                        section.showSection("DANGER");
                    } 
                }
            }
                         
            int count = postModel.getPost(0, -1, "", "", userLogin, "", "", "", "").size();
            String pageNavi = CommonUtil.getPageNavi(page, count, NEWS_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);
                        
            Template template = RenderModel.getAdminCTemplate("user_news_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminNewsUserController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    private String renderSearchPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);            

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "newsuser"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin đã post");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
            
            String id_Search = req.getParameter("postID") != null ? req.getParameter("postID") : "";            
            String title = req.getParameter("postTitle") != null ? req.getParameter("postTitle") : "";            
            String created = req.getParameter("postCreated") != null ? req.getParameter("postCreated") : "";
            String status = req.getParameter("postStatus") != null ? req.getParameter("postStatus") : "";  
            //String type = req.getParameter("postType") != null ? req.getParameter("postType") : "";
            
            SessionModel sessionModel = SessionModel.getInstance();                
            String userLogin = sessionModel.getUserLogin(req);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
//            if(type.equals("0")){ //tin tức
//                NewsModel newsModel = NewsModel.getInstance();
//                List<NewsData> lstNewsData = newsModel.getNews(0, -1, userLogin, title, status, id_Search, created, "");   
//                if (lstNewsData != null && !lstNewsData.isEmpty()) {                    
//                    for(int i = (page - 1) * NEWS_PER_PAGE; i < page * NEWS_PER_PAGE; i++){ 
//                        if(i == lstNewsData.size())
//                            break;
//                        NewsData newsData = lstNewsData.get(i);                        
//                        TemplateDataDictionary section = dic.addSection("LIST_NEWS");  
//                        section.setVariable("NEWS_LINK", "/news/edit?id=" + newsData.getId());                              
//                        section.setVariable("NEWS_TITLE", newsData.getTitle());                              
//                        Date d = new Date(newsData.getCreated());
//                        section.setVariable("CREATED", sdf.format(d));
//                        if (newsData.getStatus() == 0) {
//                            section.setVariable("STATUS", "Chờ duyệt");
//                            section.showSection("WARNING");
//                        } else if (newsData.getStatus() == 1){
//                            section.setVariable("STATUS", "Công khai");
//                        }
//                        else {
//                            section.setVariable("STATUS", "Ẩn");
//                            section.showSection("DANGER");
//                        }                                      
//                    }
//                }
//                
//                dic.showSection("NEWSTYPE");                
//                int count = lstNewsData.size();
//                String pageNavi = CommonUtil.getPageNavi(page, count, NEWS_PER_PAGE, "?" + req.getQueryString());
//                dic.setVariable("PAGENAVI", pageNavi);
//            }
            //else{
                PostModel postModel = PostModel.getInstance();
                List<PostData> lstPostData = postModel.getPost(0, -1, id_Search, "", userLogin, title, status, created, "");                                
                if (lstPostData != null && !lstPostData.isEmpty()) { 
                    for(int i = (page - 1) * NEWS_PER_PAGE; i < page * NEWS_PER_PAGE; i++){ 
                        if(i == lstPostData.size())
                            break;
                        PostData postData = lstPostData.get(i);
                        TemplateDataDictionary section = dic.addSection("LIST_NEWS"); 
                        section.setVariable("NEWS_LINK", "/post/edit?id=" + postData.getId());                              
                        section.setVariable("NEWS_TITLE", postData.getTitle());                              
                        Date d = new Date(postData.getCreated());
                        section.setVariable("CREATED", sdf.format(d));
                        if (postData.getStatus() == 0) {
                            section.setVariable("STATUS", "Chờ duyệt");
                            section.showSection("WARNING");
                        } else if (postData.getStatus() == 1){
                            section.setVariable("STATUS", "Công khai");
                        }
                        else {
                            section.setVariable("STATUS", "Ẩn");
                            section.showSection("DANGER");
                        }   
                    }
                }
                
                //dic.showSection("POSTTYPE");
                int count = lstPostData.size();
                String pageNavi = CommonUtil.getPageNavi(page, count, NEWS_PER_PAGE, "?" + req.getQueryString());
                dic.setVariable("PAGENAVI", pageNavi);
            //}
                                    
            dic.setVariable("ID_SEARCH", id_Search);
            dic.setVariable("TITLE_SEARCH", title);                                    
            dic.setVariable("CREATE_SEARCH", created);            
            if (status.equals("0")) 
                dic.showSection("WAITING");            
            else if (status.equals("1"))
                dic.showSection("PUBLISH");            
            else if(status.equals("2"))
                dic.showSection("INACTIVE");            
                        
            Template template = RenderModel.getAdminCTemplate("user_news_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminNewsUserController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
}
